package me.ezitku.shttp


//import com.readystatesoftware.chuck.ChuckInterceptor
import android.annotation.SuppressLint
import android.content.Context
import com.google.gson.GsonBuilder
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit


//private var headerses: HashMap<String, String>? = null
@SuppressLint("StaticFieldLeak")
private var context: Context? = null
var httpBuilder: SHttpBuilder? = null
private val gson by lazy {
    GsonBuilder()
//            .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
//            .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
//            .serializeNulls()
//            .registerTypeAdapter(String::class.java, StringNullAdapter())
//            .registerTypeAdapter(Integer::class.java, IntegerNullAdapter())
            .create()
}

private fun client(): OkHttpClient {
//    var mCach = Cache(File(Environment.getExternalStorageDirectory(),
//            "cachData"), 1024 * 1024 * 100)
//    var control = CacheControl.Builder().build()

    val builder = OkHttpClient.Builder()
            .retryOnConnectionFailure(httpBuilder?.retryOnConnectionFailure
                    ?: false)
            .connectTimeout(httpBuilder?.connectTimeout?:20, TimeUnit.SECONDS)
//            .addInterceptor(setHeaderInterceptor)



    if (httpBuilder?.isShowHttpLogger == true && context!=null) {
        //builder.addInterceptor(ChuckInterceptor(context))
    }


    builder.addInterceptor(setHeaderInterceptor)
    if (httpBuilder != null) {
        httpBuilder!!.interceptors.forEach {
            builder.addInterceptor(it)
        }
    }


    return builder.build()
}

private fun getRetrofit(url: String): Retrofit {
    val builder =  Retrofit.Builder()
            .baseUrl(url)
            .client(client())
//            .addConverterFactory(ToStringConverterFactory())
//            .addConverterFactory(GsonConverterFactory.create(gson))

    httpBuilder?.converterFactorys?.forEach {
        builder.addConverterFactory(it)
    }

    httpBuilder?.callAdapterFactorys?.forEach {
        builder.addCallAdapterFactory(it)
    }


    return builder.build()
}

fun <T> Context.getApi(cls: Class<T>, baseUrl: String, builder: SHttpBuilder.() -> Unit): T {
    context = this
    val _httpBuilder = SHttpBuilder()
    builder(_httpBuilder)
    httpBuilder = _httpBuilder
    return getRetrofit(baseUrl).create(cls)
}

//fun <T> getHttp(cls: Class<T>, baseUrl: String, builder: SHttpBuilder.() -> Unit): T {
//    val _httpBuilder = SHttpBuilder()
//    builder(_httpBuilder)
//    httpBuilder = _httpBuilder
//    return getRetrofit(baseUrl).create(cls)
//}


object setHeaderInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val original = chain.request()
        val request: Request
        val bui = original.newBuilder()
        httpBuilder?.headers?.forEach { bui.addHeader(it.key, "${it.value}") }
        request = bui.build()
        return chain.proceed(request)
    }
}